package com.boomsecret.lock;

import redis.clients.jedis.Jedis;

import java.util.UUID;

/**
 * Created by wangjinliang on 2018/8/8.
 */
public class RedisDistributedDemo {
    private static RedisDistributedLock LOCK = new RedisDistributedLock();

    private static final int MAX_THREAD = 20;
    private static final int EXPIRE_TIME = 3000;
    private static final String LOCK_PATH = "test_lock_path";

    public static void main(String[] args) throws Exception {
        for (int index = 0; index < MAX_THREAD; index ++) {
            new TaskThread(index).start();
            Thread.sleep(200);
        }
    }

    static class TaskThread extends Thread {
        private int threadNum;

        TaskThread(int threadNum) {
            this.threadNum = threadNum;
        }

        @Override
        public void run() {
            Jedis jedis = new Jedis("182.92.234.232",6379);
            String requestId = UUID.randomUUID().toString();
            boolean resultStatus = LOCK.tryDistributedLock(jedis, LOCK_PATH, requestId, EXPIRE_TIME);
            try {
                if (resultStatus) {
                    System.out.println(Thread.currentThread().getName() + " index --> " + this.threadNum + " 获取锁");
                    Thread.sleep(1000);
                } else {
                    System.out.println(Thread.currentThread().getName() + " index --> " + this.threadNum + " 获取锁失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (resultStatus) {
                    LOCK.releaseDistributedLock(jedis, LOCK_PATH, LOCK_PATH);
                    System.out.println(Thread.currentThread().getName() + " index --> " + this.threadNum + " 释放锁");
                }
            }
        }
    }
}